package com.plan.controller;

import com.plan.entity.User;
import com.plan.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("admin")
@Slf4j
public class AdminController {
    @Autowired
    private AdminService adminService;
    @PostMapping("register")
    public Map<String,Object> register(@RequestBody User user, String code, HttpServletRequest request){
        log.info("用户输入的信息[{}]"+user.toString());
        Map<String,Object> map = new HashMap<>();
        try{
                adminService.register(user);
                map.put("state",true);
                map.put("msg","注册成功");
        }
        catch(Exception e){
            e.printStackTrace();
            map.put("state",false);
            map.put("msg","提示："+e.getMessage());
        }
        return map;
    }

    @GetMapping("findAll")
    public Map<String,Object> findAll(Integer page,Integer rows) {
        page = page==null?1:page;
        rows = rows==null?4:rows;
        HashMap<String,Object> map=new HashMap<>();
        List<User> users= adminService.findAllUser(page, rows);
        for(int i=0;i<users.size();i++){
            if(users.get(i).getSex().equals("1")){
                users.get(i).setSex("男");
            }else{
                users.get(i).setSex("女");
            }
        }
        map.put("status",true);
        map.put("msg","请求成功");

        Integer totals=adminService.findTotalsUser();
        Integer totalsPage=totals%rows==0?totals/rows:totals/rows+1;
        map.put("users",users);
        map.put("totals",totals);
        map.put("totalPage",totalsPage);
        map.put("page",page);
        return map;
    }

    @PostMapping("updateUser")
    public Map<String,Object>update(User user){
        log.info("user信息：[{}]"+user.toString());
        Map<String,Object>map = new HashMap<>();
        try {
            adminService.saveUser(user);
            map.put("state",true);
            map.put("msg","修改成功");
        }catch(Exception e){
            e.printStackTrace();
            map.put("state",false);
            map.put("msg","修改失败");
        }
        return map;
    }

    @GetMapping("findUser")
    public  User findUser(String id){
        log.info("查询user信息的id:[{}]"+id);
        User userDB=adminService.findUser(id);
        if(userDB.getSex().equals("1")){
            userDB.setSex("男");
        }else {
            userDB.setSex("女");
        }
        return userDB;
    }

}
